<template>
  <div class="container">
    <el-dialog
      v-loading="loading"
      :visible.sync="showDialog"
      :title="editList.id?'修改学科':'新增学科'"
      width="500px"
      @close="close"
    >
      <el-form ref="form" :model="addInfo" :rules="rules">
        <el-form-item
          label="学科名称"
          label-width="80px"
          prop="subjectName"
        >
          <el-input
            v-model="addInfo.subjectName"
            placeholder="请输入学科名称"
          >1</el-input>
        </el-form-item>
        <el-form-item
          label="是否显示"
          label-width="80px"
        >
          <el-switch
            v-model="addInfo.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-button size="small" @click="close">取消</el-button>
            <el-button size="small" type="primary" @click="submit">确定</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects'
export default {
  name: 'AddSubject',
  props: {
    editList: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      showDialog: false,
      loading: false,
      addInfo: {
        subjectName: '',
        isFrontDisplay: 1
      },
      rules: {
        subjectName: [
          { required: true, message: '目录名称为必填' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹窗，重置表单校验及清除表单内容
    close() {
      this.showDialog = false
      this.$refs.form.resetFields()
      this.addInfo = {
        subjectName: '',
        isFrontDisplay: 1
      }
    },
    // 添加功能
    async submit() {
      this.loading = true
      try {
        await this.$refs.form.validate()
      } catch {
        this.loading = false
        return
      }
      if (this.addInfo.id) {
        await update({
          id: this.addInfo.id,
          subjectName: this.addInfo.subjectName,
          isFrontDisplay: this.addInfo.isFrontDisplay

        })
      } else {
        await add(this.addInfo)
      }
      this.loading = false
      this.showDialog = false
      this.$message.success('操作成功')
      this.$emit('getList')
    }
  }
}
</script>

<style scoped lang='scss'></style>
